package com.lxy.exportword.handler;

import com.lxy.exportword.common.Result;
import com.lxy.exportword.enums.ExceptionEnum;
import com.lxy.exportword.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.yaml.snakeyaml.constructor.DuplicateKeyException;

import java.nio.file.AccessDeniedException;


/** 全局异常处理类
 * @author LiuXiaoYu
 * @date 2021/7/19- 14:25
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理业务异常
     * @param bizException 自定义异常
     * @return result 通用错误返回
     */
    @ExceptionHandler(BizException.class)
    public Result<ExceptionEnum> handleException(BizException bizException){
        log.warn("业务异常:{}",bizException.getMessage(),bizException);
        return Result.error(bizException.getError(),bizException.getMessage());
    }

    @ExceptionHandler(AccessDeniedException.class)
    public Result<ExceptionEnum> handleAuthorizationException(AccessDeniedException e){
        log.warn("权限异常:{}",e.getMessage(),e);
        return Result.error(e.getMessage());
    }
    @ExceptionHandler(NoHandlerFoundException.class)
    public Result<ExceptionEnum> handlerNoFoundException(NoHandlerFoundException e) {
        log.warn("请求路径异常:{}",e.getMessage(), e);
        return Result.error(ExceptionEnum.REQUEST_PATH);
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public Result<String> handleDuplicateKeyException(DuplicateKeyException e){
        log.warn("数据库已存在该记录异常:"+e.getMessage(), e);
        return Result.error("数据库中已存在该记录");
    }

    @ExceptionHandler(RuntimeException.class)
    public Result<ExceptionEnum> handleRuntimeException(RuntimeException e){
        log.warn("运行时异常:{}",e.getMessage(),e);
        return Result.error(ExceptionEnum.ERROR,"系统异常请联系管理员");
    }
    @ExceptionHandler(IllegalArgumentException.class)
    public Result<ExceptionEnum> handleIllegalArgumentException(IllegalArgumentException e){
        log.warn("非法参数异常:{}",e.getMessage(),e);
        return Result.error(ExceptionEnum.ERROR,"请检查参数是否有误");
    }
}
